/*
 * Copyright (C) 2008  Marcelo Busico <marcelobusico@simbya.com.ar>
 * 
 * This file is part of a SIMBYA project.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gecom.app.usuarios;

import gecom.app.*;
import gecom.app.configuracion.GestorConfigurarConexion;
import java.awt.event.KeyEvent;
import javax.naming.NamingException;
import javax.swing.JOptionPane;
import simbya.framework.appserver.GestorConexion;
import simbya.framework.appserver.ServerConf;
import simbya.gecom.entidades.seguridad.UsuarioSistema;
import simbya.gecom.gestores.seguridad.GestorIniciarSesionRemote;

/**
 * Ventana para iniciar sesion en el sistema.
 * @author Marcelo Busico.
 */
public class VentanaInicioSesion extends javax.swing.JFrame {

    private GestorIniciarSesionRemote gestor;

    /** 
     * Crea un nuevo formulario VentanaInicioSesion.
     */
    public VentanaInicioSesion() {
        initComponents();
    }

    /**
     * Intenta acceder al sitema con los datos proporcionados por el usuario.
     */
    private void intentarAcceso() {
        String usuario = txtUsuario.getText();
        char[] pass = txtContrasenia.getPassword();

        if (usuario == null || pass == null || usuario.isEmpty() || pass.length == 0) {
            JOptionPane.showMessageDialog(this,
                    "Error al acceder al programa.\n" +
                    "El nombre de usuario y contraseña no pueden estar en blanco.");
            return;
        }

        try {
            gestor = (GestorIniciarSesionRemote) GestorConexion.getInstancia().getObjetoRemoto(
                    GestorIniciarSesionRemote.class);
        } catch (NamingException ex) {
            JOptionPane.showMessageDialog(this, "Error al obtener gestor de inicio de sesión" +
                    " del servidor de aplicaciones:\n" + ex.getMessage(),
                    "Error de sistema", JOptionPane.ERROR_MESSAGE);
        }
        UsuarioSistema usuarioSistema = gestor.iniciarSesion(usuario, pass);
        if (usuarioSistema != null) {
            this.dispose();
            Main.main(null);
            VentanaMenuPrincipal.getInstancia().cargarPrivilegiosDelUsuario(usuarioSistema);
        } else {
            JOptionPane.showMessageDialog(this,
                    "Error al acceder al programa.\n" +
                    "Por favor, verifique nombre de usuario y contraseña e inténtelo nuevamente.");
            txtContrasenia.setText("");
            txtContrasenia.requestFocus();
        }
    }

    /**
     * Informa al gestor la petición de salida del usuario.
     */
    private void salir() {
        try {
            gestor.salir();
        } catch (Exception ex) {
        }
        System.exit(0);
    }

    /**
     * Llama al gestor para configurar el acceso al servidor de base de datos.
     */
    public void configurarServidor() {
        setVisible(false);
        try {
            ServerConf sc = ServerConf.cargarDeArchivo(
                    ServerConf.nombreArchivo);
            new GestorConfigurarConexion(this, sc);
        } catch (Exception ex) {
            new GestorConfigurarConexion(this);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fraDatos = new javax.swing.JPanel();
        txtContrasenia = new javax.swing.JPasswordField();
        txtUsuario = new javax.swing.JTextField();
        lblUsuario = new javax.swing.JLabel();
        lblPassword = new javax.swing.JLabel();
        btnSalir = new javax.swing.JButton();
        btnIngresar = new javax.swing.JButton();
        btnConfigurar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Iniciar sesión..."); // NOI18N
        setAlwaysOnTop(true);
        setResizable(false);

        fraDatos.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        txtContrasenia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtContraseniaKeyPressed(evt);
            }
        });

        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyPressed(evt);
            }
        });

        lblUsuario.setText("Usuario:");

        lblPassword.setText("Contraseña:");

        javax.swing.GroupLayout fraDatosLayout = new javax.swing.GroupLayout(fraDatos);
        fraDatos.setLayout(fraDatosLayout);
        fraDatosLayout.setHorizontalGroup(
            fraDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fraDatosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(fraDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, fraDatosLayout.createSequentialGroup()
                        .addComponent(lblUsuario)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(fraDatosLayout.createSequentialGroup()
                        .addComponent(lblPassword)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGap(12, 12, 12)
                .addGroup(fraDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE)
                    .addComponent(txtContrasenia, javax.swing.GroupLayout.DEFAULT_SIZE, 201, Short.MAX_VALUE))
                .addContainerGap())
        );
        fraDatosLayout.setVerticalGroup(
            fraDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(fraDatosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(fraDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUsuario)
                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(fraDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPassword)
                    .addComponent(txtContrasenia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        btnIngresar.setText("Ingresar");
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        btnConfigurar.setText("Configurar");
        btnConfigurar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfigurarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnConfigurar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE)
                        .addComponent(btnIngresar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSalir))
                    .addComponent(fraDatos, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(fraDatos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalir)
                    .addComponent(btnIngresar)
                    .addComponent(btnConfigurar))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-349)/2, (screenSize.height-154)/2, 349, 154);
    }// </editor-fold>//GEN-END:initComponents
    private void txtUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.intentarAcceso();
        }
    }//GEN-LAST:event_txtUsuarioKeyPressed

    private void txtContraseniaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtContraseniaKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            this.intentarAcceso();
        }
    }//GEN-LAST:event_txtContraseniaKeyPressed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        salir();
}//GEN-LAST:event_btnSalirActionPerformed

    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
        intentarAcceso();
    }//GEN-LAST:event_btnIngresarActionPerformed

private void btnConfigurarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfigurarActionPerformed
    configurarServidor();
}//GEN-LAST:event_btnConfigurarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConfigurar;
    private javax.swing.JButton btnIngresar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JPanel fraDatos;
    private javax.swing.JLabel lblPassword;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JPasswordField txtContrasenia;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
